<template>
  <div class="about">
    <!-- 自动读取其value属性显示 -->
    <p>count: {{count}}</p>
    <p>double: {{double}}</p>
    <p>double2: {{double2}}</p>

    <hr>
    <p>msg: {{state.msg}}</p>
    <p>person.name: {{state.person}}</p>
    <p>likes[1]: {{state.likes[1]}}</p>

    <button @click="update">更新</button>
  </div>
</template>

<script lang="ts">
import {ref, computed, reactive} from 'vue'    // reference

interface State {
  msg: string;
  person: {
    name?: string,
    age?: number
  };
  likes: string[];
}

export default {

  beforeCreate () {
    console.log('beforeCreate()')
  },

  /* 
  此方法在beforeCreate()就会启动行一次
  内部的this为undefined
  vue3的所有组合API函数都在其内部调用
  */
  setup () {
    console.log('setup')
    // ref响应式对象
    const count = ref(1)
    console.log('count', count)

    // 计算属性   getter
    const double = computed(() => {
      console.log('computed double')
      return count.value * 2
    })
    console.log('double', double)

    const double2 = computed<number>({
      get () {
        console.log('getter double2')
        return count.value * 3
      },
      set (value) {
        console.log('setter double2')
        count.value = 4
      }
    })

    const state = reactive<State>({
      msg: 'abc',
      person: {
        name: 'tom'
      },
      likes: ['A', 'B']
    })


    const update = () => {
      // count.value += 1
      // double2.value += 3

      // state.msg += '--'
      // state.person.name += '---'

      // 通过下标向数组中替换元素 ==> vue2不会更新界面
      // state.likes[1] = 'C'
      // 直接添加一个新属性  ==> vue2不会更新界面
      // state.person.age = 2
      // 直接删除一个已有属性  ==> vue2不会更新界面
      delete state.person.name
    }

    return { // 返回的对象中的属性和方法模板可以直接使用
      count,
      double,
      double2,
      update,
      state
    }
  }
}
</script>